package top.kaoshanji.p1ch02d;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodType;

/**
 * 代码清单 p1ch02d-12：MethodHandles#invoker的使用示例
 * author kaoshanji
 * ^_^
 * create time 2025/1/3 19:53
 */
public class MethodHandlesExample12 {

    private static final Logger logger = LogManager.getLogger(MethodHandlesExample12.class);

    public static void main(String[] args) throws Throwable {

        new MethodHandlesExample12().invoker();

    }

    public void invoker() throws Throwable {
        logger.info("...代码清单 p1ch02d-12：MethodHandles#invoker的使用示例...");

        MethodType typeInvoker = MethodType.methodType(String.class, Object.class, int.class, int.class);
        MethodHandle invoker = MethodHandles.invoker(typeInvoker);

        MethodHandles.Lookup lookup = MethodHandles.lookup();
        MethodType typeFind = MethodType.methodType(String.class, int.class, int.class);
        MethodHandle mh1 = lookup.findVirtual(String.class, "substring", typeFind);
        MethodHandle mh2 = lookup.findVirtual(MethodHandlesExample12.class, "testMethod", typeFind);
        String result = (String) invoker.invoke(mh1, "Hello", 2, 3);
        System.out.println(result);

        result = (String) invoker.invoke(mh2, this, 2, 3);
        System.out.println(result);

    }


    public String testMethod(int arg1, int arg2) {
        return "Hello";
    }

}
